﻿/*!
Urite, the so-called "Über Write" module.
Created By NanaLich. 2010-08-20
This module is published under WTFPL v2, so you just DO WHAT THE Fxxx YOU WANT TO with it.
*/

!function () {
  var w = this,
    n = w._fn_urite || 'urite';

  w[n] ? w[n](0, 1) :
    function () {
      var u, // Über sugar
        d = document,
        o = d.write, // original write
        t = o, // "temp"???????
        x = /^([\s\S]*?<\/script(?:\s[^>]*)?>)([\s\S]*)$/i, // regular EXpression

        l = '<script type="text/ecmascript" src="',
        r = '" urite-agent="1"></script>',

        s = '', // content stack
        p = s, // pending content, init as empty ''
        f = 1; // "function should be called"

      if (o.call) t = function (v) {
        o.call(d, v);
      };

      t(l + 'data:,_data_uri_useable=1' + r);

      function urite(v, _) {
        if (!u) u = l + (w._data_uri_useable ?
            'data:,' + n + '(0,1)' : // dataURI style
            function () {
              var c = d.getElementsByTagName('script'), // collection
                i = c.length,
                a = w._src_urite || n, // address
                h; // href
              while (i-- > 0) { // LOL
                h = c[i].getAttribute('src');
                if (h && h.indexOf(a) >= 0)
                  return encodeURI(h); // common relative style
              }
              return a; // let's see if we are lucky enough ; ;
            } ()
          ) + r;

        if (_) {
          f = 1, // reset it

          v = s + p,
          p = s = '';

          if (v) t(v.replace(x, function (m, a, b, i, h) { // match, a, b, index, wHole
            p = b; // put everything after </script> in pending content, so following urite call has chance to process content correctly
            f = 0; // we won't like doubled "urite()"
            return a + u; // same reason like before, to fix webkit problem
          }));
        } else {
          s += v;
          // if we have no "urite()", make one
          if (f) f = 0, t(u); // webkit will try to run the code immediately, so write it at the last
        }
      }

      w[n] = d[n] = urite;
    } ();

} ();